<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "mkt_post".
 *
 * @property string $id
 * @property string $post_type
 * @property string $user_id
 * @property string $title
 * @property string $content
 * @property string $start_time
 * @property string $end_time
 * @property string $industry_id
 * @property string $area_id
 * @property integer $status
 * @property integer $is_anoymous
 * @property string $create_time
 * @property string $update_time
 * @property string $cooperation_reward
 * @property string $job_salary_min
 * @property string $job_salary_max
 * @property integer $job_education
 * @property integer $job_experience
 * @property integer $job_age_min
 * @property integer $job_age_max
 */
class MktPost extends \common\wosotech\base\ActiveRecord
{
    const POST_TYPE_COOPERATION = 0;
    const POST_TYPE_JOB = 1;

    const POST_STATUS_NORMAL = 0;
    const POST_STATUS_DRAFT = 1;
    const POST_STATUS_DELETED = 2;
    const POST_STATUS_WAIT_APPROVE = 3;
    
    const POST_JOB_EDUCATION_GAOZHONG = 0;
    const POST_JOB_EDUCATION_DAZHUAN = 1;
    const POST_JOB_EDUCATION_BENKE = 2;
    const POST_JOB_EDUCATION_SHUOSHI = 3;

    const POST_JOB_SALARY_0 = 0;
    const POST_JOB_SALARY_1 = 1;
    const POST_JOB_SALARY_2 = 2;
    const POST_JOB_SALARY_3 = 3;
    const POST_JOB_SALARY_4 = 4;    
    const POST_JOB_SALARY_5 = 5;
    const POST_JOB_SALARY_6 = 6;
    const POST_JOB_SALARY_7 = 7;
    const POST_JOB_SALARY_8 = 8;
    const POST_JOB_SALARY_9 = 9;

/*
    const POST_JOB_AGE_0 = 0;
    const POST_JOB_AGE_1 = 1;
    const POST_JOB_AGE_2 = 2;
    const POST_JOB_AGE_3 = 3;
    const POST_JOB_AGE_4 = 4;
    const POST_JOB_AGE_5 = 5;
    const POST_JOB_AGE_6 = 6;
    const POST_JOB_AGE_7 = 7;
*/

    public $parent_industry_id;
    public $parent_area_id;    
    
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'mkt_post';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['post_type', 'user_id', 'industry_id', 'area_id', 'status', 'is_anoymous', 'job_salary_min', 'job_salary_max', 'job_education', 'job_experience', 'job_age_min', 'job_age_max', 'cooperation_reward'], 'integer'],

            [['content', 'title'], 'required'],

            [['title'], 'string', 'max' => 20],

            [['content'], 'string'],
            
//            [['start_time', 'end_time'], 'date', 'format' => 'php:Y-m-d H:i:s'],
            [['start_time', 'end_time'], 'date', 'format' => 'php:Y-m-d'],
            
            ['user_id', 'exist',
                'targetClass' => '\common\models\MktUser',
                'targetAttribute' => 'id',
                'message' => 'User ID is not existed.'
            ],

            [['cooperation_reward'], 'required', 'on'=>'cooperation'],
            
            [['create_time', 'update_time'], 'safe'],

            [['parent_industry_id', 'parent_area_id'], 'safe'],            
            
        ];
    }
    
/*
    public function validateInput($attribute, $params)
    {
        if (self::POST_TYPE_COOPERATION == $this->post_type && 'cooperation_reward' == $attribute) {
            if (empty($this->$attribute)) {        
                $this->addError($attribute, "合作回报不能为空");
            }
        }
    }

*/

    public function getPostResponses() 
    {
        return $this->hasMany(MktPostResponse::className(), ['post_id' => 'id']);
    }

    public function getPostResponseCount() 
    {
        return $this->hasMany(MktPostResponse::className(), ['post_id' => 'id'])->count();
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'post_type' => '类型',  // 贴子类型, 0:合作, 1:招聘
            'user_id' => '作者',
            'title' => '标题',
            'content' => '描述',                        // 岗位职责, 
            'start_time' => '开始时间',
            'end_time' => '结束时间',
            'industry_id' => '行业ID',
            'area_id' => '区域ID',
            'status' => '状态',     // 0:发布, 1:下线, 2:删除
            'is_anoymous' => '匿名发布',
            'create_time' => '创建时间',
            'update_time' => '修改时间',
            'cooperation_reward' => '合作回报',
            'job_salary_min' => '月薪最低值',
            'job_salary_max' => '月薪最高值',
            'job_education' => '学历要求',        // 0:高中, 1:中专, 2:大专, 3:本科
            'job_experience' => '经验要求',     // , 0:1年经验, 2:3年经验, 3:5年经验, 4:5年以上
            'job_age_min' => '最小年龄',
            'job_age_max' => '最大年龄',
        ];
    }

    /**
     * @inheritdoc
     * @return MktPostQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new MktPostQuery(get_called_class());
    }

    public function afterFind()
    {
        $this->start_time = substr($this->start_time, 0, 10);
        $this->end_time = substr($this->end_time, 0, 10);        
        parent::afterFind();
    }

    public function beforeSave($insert) {
        if ($insert) {            
            $this->status = MktPost::POST_STATUS_WAIT_APPROVE;
        } else {
            
        }
        return parent::beforeSave($insert);
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($insert) {
            $user = MktUser::findOne($this->user_id);
            if (null !== $user) {
                $user->addGold(Yii::$app->keyStorage->get('business.golds_per_post', 10), MktGold::SOURCE_REASON_WRITE_POST, "发贴");
            }
        }
        if (!$insert) {
            if (isset($changedAttributes['status'])) 
            {
                if ($changedAttributes['status'] == MktPost::POST_STATUS_WAIT_APPROVE && $this->status == MktPost::POST_STATUS_NORMAL) {
                    if (self::POST_TYPE_JOB == $this->post_type) {
                        \common\models\WxTemplateId::sendJobPost($this, true);
                    } else {                    
                        \common\models\WxTemplateId::sendCooperatePost($this, true);                    
                    }
                }

                if ($changedAttributes['status'] == MktPost::POST_STATUS_WAIT_APPROVE && $this->status == MktPost::POST_STATUS_DELETED) {
                    if (self::POST_TYPE_JOB == $this->post_type) {
                        \common\models\WxTemplateId::sendJobPost($this, false);             
                    } else {
                        \common\models\WxTemplateId::sendCooperatePost($this, false);                                 
                    }                    
                }
                
            }        
        }        
    }

    public function getUser()
    {
        return $this->hasOne(MktUser::className(), ['id' => 'user_id']);
    }

    public function getIndustry()
    {
        return $this->hasOne(MktIndustry::className(), ['id' => 'industry_id']);
    }

    public function getArea()
    {
        return $this->hasOne(MktArea::className(), ['id' => 'area_id']);
    }

    public function getIndustryPaths()
    {
        return empty($this->industry) ? '' : $this->industry->getPaths();
    }

    public function getAreaPaths()
    {
        return empty($this->area) ? '' : $this->area->getPaths();
    }

    public function behaviors() {
        return [
            [
                'class' => \yii\behaviors\TimestampBehavior::className(),
                'createdAtAttribute' => 'create_time',
                'updatedAtAttribute' => 'update_time',
                'value' => new \yii\db\Expression('NOW()'),
            ],
        ];
    }

    public function getShortTitle() 
    {
        return $this->title;
    }
    
    public function getShortContent() 
    {
        return \common\wosotech\Util::getShortString($this->content, 10);
    }

    public function getShortStartTime() 
    {
        //return substr($this->start_time, 0 , 10);
        return date('n月j日', strtotime($this->start_time));
    }

    public static function getPostTypeOption($key = null)
    {
        $arr = array(
            static::POST_TYPE_COOPERATION => '合作',
            static::POST_TYPE_JOB => '招聘',
        );        
        return $key === null ? $arr : (isset($arr[$key]) ? $arr[$key] : '');
    }

    public static function getPostStatusOption($key = null)
    {
        $arr = array(
            static::POST_STATUS_NORMAL => '发布',
            static::POST_STATUS_WAIT_APPROVE => '审核中',            
            static::POST_STATUS_DRAFT => '下线',
            static::POST_STATUS_DELETED => '未通过审核',            
        );        
        return $key === null ? $arr : (isset($arr[$key]) ? $arr[$key] : '');
    }

    public static function getPostJobEducationOption($key = null)
    {
        $arr = array(
            static::POST_JOB_EDUCATION_GAOZHONG => '高中',
            static::POST_JOB_EDUCATION_DAZHUAN => '大专',
            static::POST_JOB_EDUCATION_BENKE => '本科',
            static::POST_JOB_EDUCATION_SHUOSHI => '硕士',            
        );        
        return $key === null ? $arr : (isset($arr[$key]) ? $arr[$key] : '');
    }

    public static function getPostJobSalaryMinOption($key = null)
    {
        $arr = array(
            static::POST_JOB_SALARY_0 => '1K',
            static::POST_JOB_SALARY_1 => '2K',
            static::POST_JOB_SALARY_2 => '3K',
            static::POST_JOB_SALARY_3 => '4K',            
            static::POST_JOB_SALARY_4 => '5K',     
        );        
        return $key === null ? $arr : (isset($arr[$key]) ? $arr[$key] : '');
    }
    
    public static function getPostJobSalaryMaxOption($key = null)
    {
        $arr = array(
            static::POST_JOB_SALARY_5 => '6K',
            static::POST_JOB_SALARY_6 => '7K',
            static::POST_JOB_SALARY_7 => '8K',
            static::POST_JOB_SALARY_8 => '9K',            
            static::POST_JOB_SALARY_9 => '10K',                                    
        );        
        return $key === null ? $arr : (isset($arr[$key]) ? $arr[$key] : '');
    }

    public static function getPostJobAgeMinOption($key = null)
    {
        $arr = array(
            18 => '18',
            25 => '25',
            30 => '30',
            40 => '40',
        );
        return $key === null ? $arr : (isset($arr[$key]) ? $arr[$key] : '');
    }

    public static function getPostJobAgeMaxOption($key = null)
    {
        $arr = array(
            25 => '25',
            35 => '35',
            45 => '45',
            55 => '55',
        );
        return $key === null ? $arr : (isset($arr[$key]) ? $arr[$key] : '');
    }
    
    public static function getPostJobExperienceOption($key = null)
    {
        $arr = array(
            0 => '1年经验',
            1 => '2年经验',
            2 => '3年经验',
            3 => '4年经验',
            4 => '5年经验+',            
        );        
        return $key === null ? $arr : (isset($arr[$key]) ? $arr[$key] : '');
    }

    public static function getPostCooperationRewardOption($key = null)
    {
        $arr = array(
            '0' => '提成2%',
            '1' => '提成3%',
            '2' => '提成5%',
            '3' => '提成8%',
            '4' => '提成12%',
        );
        return $key === null ? $arr : (isset($arr[$key]) ? $arr[$key] : '');
    }

    public static function editStatusAjax($params)
    {
        $model = MktPost::findOne($params['id']);
        $model->status = $params['status'];
        $result = $model->save(false);
        if ( true !== $result) {
            yii::error(print_r($model->getErrors(), true));
            return \yii\helpers\Json::encode(['code' => 1, 'data' => 'save error']);
        }
        return \yii\helpers\Json::encode(['code' => 0, 'data' => 'OK']);
    }

    //\common\models\MktPost::deleteTimeoutData();
    public static function deleteTimeoutData()
    {
        yii::warning('BEGIN ' . __METHOD__);
        
        $models = MktChat::find()
            ->andWhere(['cat' => MktChat::CAT_ADD_FRIEND])
            ->andWhere(['approved' => MktChat::APPROVE_STATUS_WAIT])
            ->andWhere(['<', 'create_time', date("Y-m-d H:i:s", time() - 72*3600)])
            //->andWhere(['<', 'create_time', date("Y-m-d H:i:s", time() - 60)])
            ->all();
        foreach($models as $model) {
            $model->sender->addGold(Yii::$app->keyStorage->get('business.golds_per_friend', 10), MktGold::SOURCE_REASON_APPLY_FRIEND, "超时取消{{$model->sender->name}}向{$model->recver->name}申请加好友");
            $model->approved = MktChat::APPROVE_STATUS_IGNORE;
            $model->save();
        }

        $models = MktChat::find()
            ->andWhere(['cat' => MktChat::CAT_ADD_FRIEND])
            ->andWhere(['approved' => MktChat::APPROVE_STATUS_IGNORE])
            ->andWhere(['<', 'create_time', date("Y-m-d H:i:s", time() - 90*24*3600)])
            ->all();
        foreach($models as $model) {
            $model->delete();
        }

        // 删除超过3个月的已做delete标志的聊天
        $models = MktChat::find()
            ->andWhere(['cat' => MktChat::CAT_FRIEND_MESSAGE])
            ->andWhere(['is_deleted' => 1])
            ->andWhere(['<', 'create_time', date("Y-m-d H:i:s", time() - 90*24*3600)])
            ->all();
        foreach($models as $model) {
            $model->delete();
        }

        // 删除超过3个月的已阅读的post
        $models = MktPost::find()
            ->andWhere(['not', ['status' => MktPost::POST_STATUS_NORMAL]])
            ->andWhere(['<', 'create_time', date("Y-m-d H:i:s", time() - 90*24*3600)])
            ->all();
        foreach($models as $model) {
            $model->delete();
        }

        // 删除超过6个月的已阅读的post response
        $models = MktPostResponse::find()
            ->andWhere(['is_read' => 1])
            ->andWhere(['<', 'create_time', date("Y-m-d H:i:s", time() - 180*24*3600)])
            ->all();
        foreach($models as $model) {
            $model->delete();
        }

        yii::warning('END ' . __METHOD__);        
    }

}
